from rest_framework import serializers
from system.models import Dept
from django.db.models import F


class DeptSerializer(serializers.ModelSerializer):
    class Meta:
        model = Dept
        fields = ['createBy', 'createTime', 'deptSort', 'enabled', 'hasChildren', 'id', 'label',
                  'leaf', 'name', 'pid', 'subCount', 'updateBy', 'updateTime']

    createBy = serializers.SerializerMethodField()

    def get_createBy(self, obj):
        return obj.create_by

    label = serializers.SerializerMethodField()

    def get_label(self, obj):
        return obj.name

    leaf = serializers.SerializerMethodField()

    def get_leaf(self, obj):
        if obj.sub_count:
            return False
        else:
            return True

    subCount = serializers.SerializerMethodField()

    def get_subCount(self, obj):
        return obj.sub_count

    deptSort = serializers.SerializerMethodField()

    def get_deptSort(self, obj):
        return obj.dept_sort

    hasChildren = serializers.SerializerMethodField()

    def get_hasChildren(self, obj):
        if obj.sub_count:
            return True
        else:
            return False

    createTime = serializers.SerializerMethodField()

    def get_createTime(self, obj):
        return obj.create_time

    updateBy = serializers.SerializerMethodField()

    def get_updateBy(self, obj):
        return obj.update_by

    updateTime = serializers.SerializerMethodField()

    def get_updateTime(self, obj):
        return obj.update_time


class CreateDeptSerializer(serializers.ModelSerializer):
    class Meta:
        model = Dept
        fields = ['deptSort', 'enabled', 'id', 'isTop', 'name', 'pid', 'subCount']

    deptSort = serializers.CharField(read_only=True)
    isTop = serializers.CharField(read_only=True)
    subCount = serializers.CharField(read_only=True)

    def validate(self, attrs):
        request = self.context.get('request')
        attrs['create_by'] = request.user.username
        attrs['dept_sort'] = request.data.get('deptSort')
        attrs['sub_count'] = request.data.get('subCount')
        if request.data.get('isTop') == '0':
            # 给父部门的sub_count + 1
            # pid  父部门的id
            self._add_sub_count(request.data.get('pid'))
        return attrs

    def _add_sub_count(self, parent_id):
        Dept.objects.filter(pk=parent_id).update(sub_count=F('sub_count') + 1)

    def create(self, validated_data):
        return super().create(validated_data)


class UpdateDeptSerializer(serializers.ModelSerializer):
    class Meta:
        model = Dept
        fields = ['createBy', 'createTime', 'deptSort', 'enabled', 'hasChildren', 'id',
                  'isTop', 'label', 'leaf', 'name', 'pid', 'subCount', 'updateBy', 'updateTime']

    createBy = serializers.CharField(read_only=True)
    createTime = serializers.CharField(read_only=True)
    deptSort = serializers.CharField(read_only=True)
    hasChildren = serializers.CharField(read_only=True)
    isTop = serializers.CharField(read_only=True)
    label = serializers.CharField(read_only=True)
    leaf = serializers.CharField(read_only=True)
    subCount = serializers.CharField(read_only=True)
    updateBy = serializers.CharField(read_only=True)
    updateTime = serializers.CharField(read_only=True)

    def validate(self, attrs):
        request = self.context.get('request')
        attrs['update_by'] = request.user.username
        attrs['sub_count'] = request.data.get('subCount')
        attrs['dept_sort'] = request.data.get('deptSort')
        return attrs

    def update(self, instance, validated_data):
        """
        1. 先判断是否修改为顶级部门
            1. 把当前修改部门的pid置空,
            2. sub_count = 0
            3. 修改前父部门的sub_count - 1
        2. 如果不是(次级部门之间的互相继承, 顶级部门修改为次级部门)
            1. 原父部门的sub_count - 1, 现父部门的sub_count + 1
            2. 改变继承关系
        :param instance:
        :param validated_data:
        :return:
        """
        request = self.context.get('request')
        if int(request.data.get('isTop')) > 0 and request.data.get('pid'):   # 修改为顶级部门
            parent = instance.pid                # 修改前的父部门的部门对象
            Dept.objects.filter(id=parent.pk).update(sub_count = F('sub_count') - 1)
            return super().update(instance, validated_data)
        else:          # (次级部门之间的互相继承, 顶级部门修改为次级部门)
            dept_id = request.data.get('id')                    # 自己的id
            parent_id = request.data.get('pid')                # 现继承的父部门id
            dept = Dept.objects.filter(pk=dept_id).first()     # 部门自己
            Dept.objects.filter(pk=parent_id).update(sub_count = F('sub_count') + 1) # 新继承的部门
            Dept.objects.filter(pk=dept.pid_id).update(sub_count =  F('sub_count') - 1)
            return super().update(instance, validated_data)


class DeptSuperiorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Dept
        fields = ['createBy', 'createTime', 'deptSort', 'enabled','pid',
                  'hasChildren', 'id', 'label', 'leaf', 'name', 'subCount', 'updateTime']

    createBy = serializers.SerializerMethodField()
    def get_createBy(self, obj):
        return obj.create_by

    createTime = serializers.SerializerMethodField()
    def get_createTime(self, obj):
        return obj.create_time

    deptSort = serializers.SerializerMethodField()
    def get_deptSort(self, obj):
        return obj.dept_sort

    enabled = serializers.SerializerMethodField()
    def get_enabled(self, obj):
        return obj.enabled

    hasChildren = serializers.SerializerMethodField()
    def get_hasChildren(self, obj):
        if obj.sub_count > 0:
            return True
        else:
            return False

    label = serializers.SerializerMethodField()
    def get_label(self, obj):
        return obj.name

    leaf = serializers.SerializerMethodField()
    def get_leaf(self, obj):
        if obj.sub_count < 0:
            return True
        else:
            return False

    subCount = serializers.SerializerMethodField()
    def get_subCount(self, obj):
        return obj.sub_count

    # updateBy = serializers.SerializerMethodField()
    # def get_updateBy(self, obj):
    #     return obj.update_by

    updateTime = serializers.SerializerMethodField()
    def get_updateTime(self, obj):
        return obj.update_time